package com.itheima.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.entity.YddUser;
import com.itheima.service.YddUserService;
import com.itheima.untils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/home/index")
@Slf4j
public class cUserController {
    @Autowired
    private YddUserService yddUserService;

    /**
     * 前台登录
     * @param yddUser
     * @return
     */
    @PostMapping("/login")
    public R<HashMap<String, String>> login(@RequestBody YddUser yddUser) {
        String pwd = yddUser.getPassword();
        pwd = DigestUtils.md5DigestAsHex(pwd.getBytes(StandardCharsets.UTF_8));

        LambdaQueryWrapper<YddUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YddUser::getMobile, yddUser.getMobile());

        YddUser user = yddUserService.getOne(wrapper);

        String password = user.getPassword();

        if (pwd.equals(password)) {


            Map<String, Object> map = new HashMap<>();
            map.put("id", user.getId());
            map.put("username", user.getUsername());

            String token = JwtUtils.generateToken(map);
            HashMap<String, String> tokenMap = new HashMap<>();
            tokenMap.put("token", token);

            return R.success(tokenMap);
        }
        return R.error("登录失败,用户不存在或者密码错误");
    }
}
